const app = getApp();
const requestUtil = require("../../../utils/request");
const api = require("../../../config/api");
const dateTimePicker = require('../../../utils/dateTimePicker');
const common = require('../../../utils/common');
const QQMapWX = require('../../../utils/qqmap-wx-jssdk');
var qqmapsdk;
import QRCode from '../../../utils/weapp-qrcode.js';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        modalName: 'loading',
        picUrl: api.picUrl,
        pt: 0,
        inputMap: {},
        dateTime1: null,
        dates:[],
        startYear: 2022,
        endYear: 2050,
        mapRegions: {},
        region: ['广东省', '佛山市', '禅城区'],
        signDraw: {},
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        qqmapsdk = new QQMapWX({
            key: api.qqmapid
        });
        let that = this;
        let answerId = options.answerId;
        let questionId = options.questionId;
        if(options.q) {
            let params = common.getQueryParams(options.q)
            answerId = params.answerId;
            questionId = params.questionId; 
        }
        if(app.globalData.employeeInfo || app.globalData.customInfo) {
            that.onInit(answerId, questionId);
        }else {
            app.loginCallback = () => {
                that.onInit(answerId, questionId);
            }
        }
    },
    onInit(answerId, questionId){
        var dataObj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
        this.setData({
            userInfo: app.globalData.employeeInfo,
            userType: app.globalData.userType,
            answerId: answerId,
            dateTime1: dataObj.dateTime,
            dateTimeArray1: dataObj.dateTimeArray
        });
        if(answerId) this.questionAnswerDetail(answerId);
        if(questionId) this.questionDetail(questionId);
    },
    async questionDetail(id){
        let that = this;
        let res = await requestUtil.request("POST", api.urls.questionDetail, {id: id})
        let qdetail = res.data.data;
        qdetail.questionContent = JSON.parse(qdetail.questionContent);
        let formData = qdetail.questionContent.qData;
        if(qdetail.questionType == 2 && that.data.answerId) {//调用问卷，先员工填写后客户填写
            formData = qdetail.questionContent.wData;
        }
        let dates = that.data.dates;
        let inputMap = that.data.inputMap;
        let dateTime1 = that.data.dateTime1;
        let dateTimeArray1 = that.data.dateTimeArray1;
        for(let i in formData) {
            if(formData[i].type == 'date') {
                let name = formData[i].title;
                dates.push({
                    name: name, dateTime: dateTime1,
                    dateTimeArray: dateTimeArray1
                });
                inputMap[name] = dateTimeArray1[0][dateTime1[0]] + '-' + dateTimeArray1[1][dateTime1[1]] + '-' + dateTimeArray1[2][dateTime1[2]] + ' ' + dateTimeArray1[3][dateTime1[3]] + ':' + dateTimeArray1[4][dateTime1[4]];
            }
        }
        if(that.data.userType == 1 && qdetail.questionType == 2 && !that.data.adetail) {
            inputMap["userName"] = that.data.userInfo.name;
            that.userList(id);
        }
        let questionData = qdetail.questionContent.qData;
        if(that.data.adetail != null && qdetail.questionType == 2) {
            questionData = qdetail.questionContent.wData;
        }
        that.setData({
            qdetail: qdetail,
            questionData: questionData,
            inputMap: inputMap,
            dates: dates,
            modalName: null,
        })
        let signDraw = that.data.signDraw;
        for(var i in questionData) {
            if(questionData[i].type == 'sign') {
                var context = wx.createCanvasContext(questionData[i].title);
                context.beginPath()
                context.setStrokeStyle("#000000")
                context.setLineWidth(2);
                signDraw[questionData[i].title] = {context: context, hasDraw: false, src: null};
            }
        }
        that.setData({
            signDraw: signDraw
        })
        if(that.data.adetail) {
            that.formatAnswerResult();
        }
    },
    async questionAnswerDetail(id){
        if(!id) return;
        let that = this;
        let res = await requestUtil.request("POST", api.urls.questionAnswerDetail, {id: id})
        let adetail = res.data.data;
        adetail.answerContent = JSON.parse(adetail.answerContent);
        let pt = adetail.questionType;
        if(adetail.questionType == 2 && that.data.userType == 2 && !adetail.answerContent.wResult) {
            pt = 0;
        }
        that.setData({
            adetail: adetail,
            pt: pt,
        })
        that.questionDetail(adetail.questionId);
        that.getQuestionEwm(api.urls.questionEwm + "?answerId=" + id);
    },
    formatAnswerResult() {
        let questionContent = this.data.qdetail.questionContent;
        let answerContent = this.data.adetail.answerContent;
        let answerResult = {};
        if(answerContent['qResult']) {
            for(var i in questionContent['qData']) {
                for(var j in answerContent['qResult']) {
                    if(questionContent['qData'][i].title == answerContent['qResult'][j].title) {
                        questionContent['qData'][i].answer = answerContent['qResult'][j].answer;
                        break;
                    }
                }
            }
            answerResult['qData'] = questionContent['qData'];
        }
        if(answerContent['wResult']) {
            for(var i in questionContent['wData']) {
                for(var j in answerContent['wResult']) {
                    if(questionContent['wData'][i].title == answerContent['wResult'][j].title) {
                        questionContent['wData'][i].answer = answerContent['wResult'][j].answer;
                        break;
                    }
                }
            }
            answerResult['wData'] = questionContent['wData'];
        }
        this.setData({
            answerResult: answerResult
        })
        
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    getQuestionEwm(api){
        console.log('--ewm api:' + api);
        new QRCode('questionQrcode',{
            text: api,
            width: 160,
            height: 160,
            colorDark: '#2196F3',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.L, // 二维码可辨识度
            callback: (res) => {
              console.log(res.path)
            }
        })
    },
    showModal(e) {
        this.setData({
          modalName: e.currentTarget.dataset.target
        })
    },
    hideModal(e) {
        this.setData({
          modalName: null
        })
    },
    changeDateTime1(e) {
        let name = e.currentTarget.dataset.name;
        let dates = this.data.dates;
        for(let i in dates) {
            if(dates[i].name == name) {
                let inputMap = this.data.inputMap;
                let dateTimeArray1 = this.data.dateTimeArray1;
                let dateTime1 = e.detail.value;
                dates[i].dateTime = dateTime1;
                dates[i].dateTimeArray = dateTimeArray1;
                inputMap[name] = dateTimeArray1[0][dateTime1[0]] + '-' + dateTimeArray1[1][dateTime1[1]] + '-' + dateTimeArray1[2][dateTime1[2]] + ' ' + dateTimeArray1[3][dateTime1[3]] + ':' + dateTimeArray1[4][dateTime1[4]];
                this.setData({
                    inputMap: inputMap,
                    dates: dates
                });
                break;
            }
        }
    },
    changeDateTimeColumn1(e) {
        let name = e.currentTarget.dataset.name;
        let dates = this.data.dates;
        for(let i in dates) {
            if(dates[i].name == name) {
                var arr = dates[i].dateTime, dateArr = dates[i].dateTimeArray;
                arr[e.detail.column] = e.detail.value;
                dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
            
                this.setData({ 
                    dates: dates
                });
                break;
            }
        }
    },
    getLocation(e){
        let that = this;
        let name = e.currentTarget.dataset.name;
        wx.showLoading({
          title: '请稍等...',
        })
        wx.getLocation({
            type: 'gcj02',
            success (res) {
              const latitude = res.latitude
              const longitude = res.longitude
              qqmapsdk.reverseGeocoder({
                location: {
                    latitude: latitude,
                    longitude: longitude
                },
                success(res){
                    console.log(res);
                    let mapRegions = that.data.mapRegions;
                    let inputMap = that.data.inputMap;
                    mapRegions[name] = [];
                    mapRegions[name][0] = res.result.address_component.province;
                    mapRegions[name][1] = res.result.address_component.city;
                    mapRegions[name][2] = res.result.address_component.district;
                    inputMap[name] = res.result.formatted_addresses.recommend;
                    that.setData({
                        inputMap: inputMap,
                        mapRegions: mapRegions,
                    })
                    wx.hideLoading();
                },fail(res){
                    console.log(res);
                    wx.hideLoading();
                }
              })
            }
        })
    },
    RegionChange: function(e) {
        let name = e.currentTarget.dataset.name;
        let mapRegions = this.data.mapRegions;
        mapRegions[name] = e.detail.value;
        this.setData({
            mapRegions: mapRegions
        })
    },
    formValue(e) {
        let name = e.currentTarget.dataset.name;
        let inputMap = this.data.inputMap;
        inputMap[name] = e.detail.value;
        this.setData({
          inputMap: inputMap
        })
    },
    async userList(qId){
        let that = this;
        let res = await requestUtil.request("GET", api.urls.questionUserList, {questionId: qId});
        that.setData({
            uList: res.data.data,
        })
    },
    formSubmit: async function(e) {
        let that = this;
        let data = that.data.inputMap;
        let params = {
            questionId: that.data.qdetail.id
        };
        if(that.data.userType == 1) {
            params['userId'] = app.globalData.employeeInfo.id;
            params['userName'] = app.globalData.employeeInfo.name;
            if(!that.data.adetail && that.data.qdetail.questionType == 2 && !data["userName"]) {
                wx.showToast({
                    title: '请选择员工',
                    icon: 'error',
                    duration: 2000
                })
                return;
            }
            params['workUserNames'] = data["userName"];
        }else {
            params['custId'] = app.globalData.customInfo.id;
        }
        let formData = that.data.qdetail.questionContent.qData;
        let contentKey = "qResult";
        let answerContent = {};
        if(that.data.qdetail.questionType == 2 && that.data.adetail){
            params['id'] = that.data.adetail.id;
            formData = that.data.qdetail.questionContent.wData;
            contentKey = "wResult";
            answerContent = that.data.adetail.answerContent;
        }
        if(!answerContent[contentKey]) {
            answerContent[contentKey] = [];
        }
        for(let i in formData) {
            if(!data[formData[i].title] && formData[i].must == 'on') {
                wx.showToast({
                    title: '请填写必填问题',
                    icon: 'error',
                    duration: 2000
                })
                return;
            }
            let answer = data[formData[i].title];
            if(formData[i].type == 'map') {
                if(data[formData[i].title]) {
                    let v = that.data.mapRegions[formData[i].title];
                    if(!v) v = that.data.region;
                    answer = v.toString() + " " + answer;
                }
            }else {
               answer = data[formData[i].title];
            }
            answerContent[contentKey].push({title: formData[i].title, answer: answer});
        }
        if(!that.data.isSubmmit) {
            that.setData({
                isSubmmit: true
            })
        }else {
            return;
        }
        wx.showLoading({title: '提交中，请稍候..'})
        params.answerContent = JSON.stringify(answerContent);
        let res = await requestUtil.request("POST", api.urls.questionAnswerAdd, params);
        if(res.data.code == 0) {
            wx.showToast({title: '提交成功', icon: 'success',duration: 2000 })
            params.answerContent = answerContent;
            params.createTime = res.data.data.createTime;
            that.setData({
                pt: that.data.qdetail.questionType,
                adetail: params,
            })
            this.formatAnswerResult();
            if(that.data.userType == 1){
                that.getQuestionEwm(api.urls.questionEwm + "?answerId=" + res.data.data.id);
            }
        }else {
            wx.showToast({title: res.data.msg, icon: 'error',duration: 3000 })
            that.setData({
                isSubmmit: false
            })
            wx.hideLoading();
        }
    },
    changeSelectUser(e) {
        let name = e.detail.value;
        let inputMap = this.data.inputMap;
        inputMap["userName"] = name.toString();
        this.setData({
            inputMap: inputMap
        })
    },
    touchstart(e) {
        let name = e.target.id;
        let signDraw = this.data.signDraw;
        var context = signDraw[name].context;
        context.moveTo(e.touches[0].x, e.touches[0].y);
        signDraw[name].context = context;
        signDraw[name].hasDraw = true;
        this.setData({
            signDraw: signDraw
        });
    },
    touchmove(e) {
        var x = e.touches[0].x;
        var y = e.touches[0].y;
        let name = e.target.id;
        let signDraw = this.data.signDraw;
        var context = signDraw[name].context;
        context.setLineWidth(3);
        context.lineTo(x, y);
        context.stroke();
        context.setLineCap('round');
        context.clearRect(0, 0);
        context.draw(true);
        context.moveTo(x, y);
    },
    reSign(e) { //重新画
        let name = e.currentTarget.dataset.name;
        let signDraw = this.data.signDraw;
        var context = signDraw[name].context;
        context.clearRect(0, 0);
        context.draw(); //清空画布
        signDraw[name].context = context;
        signDraw[name].hasDraw = false;
        this.setData({
            signDraw: signDraw
        });
    },
    signCancel(e) {
        let name = e.currentTarget.dataset.name;
        let inputMap = this.data.inputMap;
        let signDraw = this.data.signDraw;
        var context = signDraw[name].context;
        context.draw(); //清空画布
        signDraw[name].hasDraw = false;    
        signDraw[name].context = context;
        signDraw[name].src = null;
        inputMap[name] = null;
        this.setData({
            signDraw: signDraw,
            inputMap: inputMap,
        });
    },
    signOk(e) {
        let that = this;
        let name = e.currentTarget.dataset.name;
        
        let signDraw = that.data.signDraw;
        var context = signDraw[name].context;
        if(!signDraw[name].hasDraw){
            wx.showModal({
                title: '提示',
                content: '签字是空白的 没有签字',
                success (res) {
                }
            })
            return;
        }else{
          context.draw(true, wx.canvasToTempFilePath({
            canvasId: name,
            success(res) {
              wx:wx.uploadFile({
                filePath: res.tempFilePath,
                name: 'file',
                url: api.urls.addSignAttch,
                formData: {
                    relationType: 'signDraw',
                    attachType: 'image',
                    userType: that.data.userType,
                    operatorId: that.data.userType == 1 ? app.globalData.employeeInfo.id : app.globalData.customInfo.id
                },
                success: (result) => {
                    signDraw[name].src  = res.tempFilePath;
                    let inputMap = that.data.inputMap;
                    inputMap[name] = JSON.parse(result.data).data.attachUrl;
                    that.setData({
                      signDraw: signDraw,
                      inputMap: inputMap,
                    })
                },
                fail: (res) => {
                    wx.showToast({ title: '请求失败,请刷新后重试', icon: 'none' });
                },
              })
            }
          }))
        }
    },
})